<!--这是店铺装修-编辑首页轮播图组件-->
<template>
  <div class="app-container">
    <el-form
      v-loading="formLoading"
      :model="postForm"
      :rules="rules"
      ref="postForm"
      label-width="220px"
      label-position="right"
    >
      <el-form-item label="选择轮播图：">
        <el-radio-group v-model="postForm.grade" @change="selectCategory">
          <el-radio :label="1">一级首页轮播图</el-radio>
          <el-radio :label="2">二级首页轮播图</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分类选择：" v-if="showSeconde">
        <el-select v-model="postForm.catId" placeholder="请选择">
          <el-option
            v-for="item in catList"
            :key="item.catId"
            :label="item.name"
            :value="item.catId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序号：" prop="sort">
        <el-input
          type="number"
          v-model.number="postForm.sort"
          placeholder="请输入排序号"
          style="width: 650px"
        ></el-input>
      </el-form-item>
      <el-form-item label="链接：" prop="link">
        <el-input v-model="postForm.link" placeholder="请输入图片链接" style="width: 650px"></el-input>
      </el-form-item>
      <!-- <el-form-item label="图片(宽750*高325)：" prop="url">
        <el-upload
          ref="avatarUpload"
          name="avatar"
          :action="imageUploadUrl"
          list-type="picture"
          :before-upload="handleBeforeUpload"
          :on-success="handleAvatarSuccess"
          :on-remove="handleAvatarRemove"
          :on-exceed="handleAvatarExceed"
          :file-list="avatarList"
          :limit="1"
          :auto-upload="false"
          style="width: 650px">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitAvatarUpload">上传到服务器
          </el-button>
        </el-upload>
      </el-form-item>-->
      <el-form-item label="图片(宽750*高325)：" prop="url">
        <div class="clearfix">
          <img
            class="fl margin-r"
            :src="postForm.url"
            @error="setDefultImg"
            width="240"
            height="120"
            alt
          />
          <el-upload
            class="fl"
            ref="avatarUpload"
            name="avatar"
            :action="imageUploadUrl"
            list-type="picture"
            :before-upload="handleBeforeUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            :auto-upload="true"
            style="width: 420px"
          >
            <el-button class="el-btn" slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3m</div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-loading="btnLoading" icon="el-icon-check" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getImage, addImage, updateImage } from "@/api/systemManage";
// import imageComponent from '@/components/imageComponent'
// import ImageCropper from '@/components/ImageCropper'
import defultImg from "@/assets/defult270.png";
const postForm = {
  sort: null, // 排序号
  link: null, // 图片链接
  url: " ",
  type: 1
};

const validateNumber = (rule, value, callback) => {
  if (value && isNaN(value)) {
    callback("请输入正确的数值");
  } else {
    if (value < 0 || value == null || value == "") {
      callback("请输入正确的数值");
    }
    callback();
  }
};

const rules = {
  sort: [{ required: true, trigger: "blur", validator: validateNumber }],
  url: [{ required: true, message: "请上传图片", trigger: "submitForm" }]
  // link: [{ required: true, message: '请输入图片链接地址', trigger: 'submitForm' }]
};

export default {
  // components: {
  //   imageComponent,
  //   ImageCropper
  // },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      postForm: Object.assign({}, postForm),
      rules,
      imageUploadUrl: process.env.BASE_API + "/common/companies/imageUpload",
      formLoading: false,
      btnLoading: false,
      avatarList: [],
      imagecropperShow: false,
      imagecropperKey: 0,
      showSeconde: false,
      catList: []
    };
  },
  created() {
    this.initData();
    this.catList = JSON.parse(localStorage.getItem("catList"));
  },

  methods: {
    selectCategory(val) {
      console.log(val);
      if (val == 2) {
        this.showSeconde = true;
      } else {
        this.showSeconde = false;
        this.postForm.catId = null
      }
    },
    initData() {
      if (this.isEdit) {
        const imageId = this.$route.params.picId;
        getImage(imageId)
          .then(res => {
            if (res.data.statusCode == 200) {
              this.postForm = res.data.data;
              if (res.data.data.grade == 2) {
                this.showSeconde = true;
              }
              // this.postForm = res.data.data;
              if (this.postForm.url) {
                this.avatarList = [{ url: this.postForm.url }];
              }
            } else {
              this.$message({
                message: "数据获取失败，请稍后再试！",
                type: "warning"
              });
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    setDefultImg(e) {
      e.target.src = defultImg;
    },
    handleAvatarSuccess(response, file, fileList) {
      if (response.statusCode == 200) {
        this.postForm.url = response.data.imageUrl;
        this.$message({
          message: "上传成功!",
          type: "info"
        });
      } else {
        this.$message({
          message: "上传失败，请稍候再试!",
          type: "info"
        });
      }
    },
    handleBeforeUpload(file) {
      const isImg = file.type == "image/jpeg" || file.type == "image/png";
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isImg) {
        this.$message.warning("上传图片只能是 JPG 或 PNG 格式");
      }
      if (!isLt3M) {
        this.$message.warning("上传图片大小不能超过 3MB");
      }
      return isImg && isLt3M;
    },
    handleCreate() {
      addImage(this.postForm)
        .then(res => {
          if (res.data.statusCode == 200) {
            this.$notify({
              title: "提示",
              message: "提交成功!",
              type: "success"
            });
            this.btnLoading = false;
            this.formLoading = false;
            this.close();
          } else {
            this.btnLoading = false;
            this.formLoading = false;
            this.$notify({
              title: "提示",
              message: "提交失败!",
              type: "error"
            });
          }
        })
        .catch(err => {
          this.btnLoading = false;
          this.formLoading = false;
          console.log(err);
        });
    },
    handleUpdate() {
      const imageId = this.$route.params.picId;
      updateImage(imageId, this.postForm)
        .then(res => {
          if (res.data.statusCode == 200) {
            this.$notify({
              title: "提示",
              message: "提交成功!",
              type: "success"
            });
            this.btnLoading = false;
            this.formLoading = false;
            this.close();
          } else {
            this.btnLoading = false;
            this.formLoading = false;
            this.$notify({
              title: "提示",
              message: "提交失败!",
              type: "error"
            });
          }
        })
        .catch(err => {
          this.btnLoading = false;
          this.formLoading = false;
          console.log(err);
        });
    },
    close() {
      this.$store.dispatch("delVisitedViews", this.$route).then(views => {
        const latestView = views.slice(-1)[0];
        if (latestView) {
          const activeName = localStorage.getItem("manageBar");
          this.$router.push({
            name: "manage",
            params: { activeName: activeName }
          }); // latestView.path
        } else {
          this.$router.push("/");
        }
      });
    },
    submitForm() {
      if (this.postForm.url == null) {
        this.$message.warning("请上传图片");
        return;
      }

      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (this.btnLoading) {
            return;
          }
          this.btnLoading = true;
          this.formLoading = true;
          if (this.isEdit) {
            this.handleUpdate();
          } else {
            this.handleCreate();
          }
        } else {
          console.log("error submit!");
          return false;
        }
      });
    }
  }
};
</script>
<style scoped>
</style>
